const WS_HOST = '192.168.85.129'
const WS_PORT = 9527

class WS {
  ws
  constructor () {
    if (!('WebSocket' in window)) {
      console.error('您的浏览器不支持WebSocket')
    }
  }

  open (f, errorF) {
    this.ws = new WebSocket('ws://' + WS_HOST + ':' + WS_PORT)
    this.ws.onopen = () => {
      f()
    }
    this.ws.onerror = () => {
      errorF('WebSocket 连接失败！')
    }
  }

  close () {
    this.ws.close()
  }

  message (f) {
    this.ws.onmessage = (e) => {
      f(JSON.parse(e.data))
    }
  }

  // 发送消息
  send (c) {
    const DEFAULT = {
      event: 'msg',
      from: null,
      to: 'all',
      data: {},
      type: 'text',
      time: new Date().getTime()
    }
    c = Object.assign(DEFAULT, c)
    this.ws.send(JSON.stringify(c))
  }
}
export default new WS()
